const { guid } = require('./helper');

class WorkerFactory {
    constructor(workerFn) {
        this._map = new Map();
        let worker = this._worker = new Worker(URL.createObjectURL(new Blob([`(${workerFn.toString()})()`])));
        worker.onmessage = ({ data }) => {
            let { id, result = true } = data;
            let t = this._map.get(id);
            if (t) {
                this._map.delete(id);
                let { resolve, reject } = t;
                if (result) {
                    resolve(data.data);
                } else {
                    reject(data.data);
                }
            }
        };
    }

    get worker() {
        return this._worker;
    }

    postMessage(type, data) {
        return new Promise((resolve, reject) => {
            let id = guid();
            this.worker.postMessage({ id, data: { type, data } });
            this._map.set(id, { resolve, reject });
        });
    }
}

module.exports = {
    get(worker) {
        return new WorkerFactory(worker);
    }
};